<?php
namespace App\Service;

use App\Models\Admin\Basic as BasicModel;
use App\Models\Admin\BasicBatch as BasicBatchModel;
use App\Models\Admin\UserGroupMember;
use App\Models\User as UserModel;
use App\Models\Admin\BasicMember as BasicMemberModel;
use App\Models\Admin\Org as OrgModel;

class BasicService extends BaseService{
    protected $modelName = "Admin.Basic";
    /*
     * 考场列表
     */
    public function getBasicList($limit,$search) {
        $user_org = $this->getOrgIds();
        $user_category = $this->getCategoryIds();
        $res = BasicModel::
            join('category as c','basic.category_id','c.id')
            ->join('org as o','basic.org_id','o.id')
            ->select('basic.*','c.name as category_name','o.name as org_name')
            ->where(function($query) use ($search){
                if(!empty($search['keyword'])){
                    $query->where("basic","like","%".$search['keyword']."%");
                }
                if(!empty($search['id'])){
                    $query->where("basic.id",$search['id']);
                }
                if(!empty($search['category_id'])){
                    $query->where("category_id",$search['category_id']);
                }
                if(!empty($search['index_org_code'])){
                    $query->where("org_code","like",$search['index_org_code']."%");
                }
            })
        ->whereIn("org_id",$user_org)
        ->whereIn("category_id",$user_category)
        ->orderBy('id','desc')->paginate($limit)->toArray();
        return $res;
    }
    /*
     * 考试批次列表
     */
    public function getBasicBatchList($limit,$search){
        $res = BasicBatchModel::
            where(function($query) use ($search){
                if(!empty($search['basic_id'])){
                    $query->where("basic_id",$search['basic_id']);
                }
            })
            ->orderBy('id','desc')->paginate($limit)->toArray();
        foreach ($res['data'] as $k=>$v){
            $res['data'][$k]['exam_start_at'] = date("Y-m-d H:i:s",$v['exam_start_at']);
            $res['data'][$k]['exam_end_at'] = date("Y-m-d H:i:s",$v['exam_end_at']);
        }
        return $res;
    }
    /*
     * 删除考场
     */
    public function delete($ids) {
        return BasicModel::where(function($query) use ($ids){
            if(is_array($ids)){
                $query->whereIn('id',$ids)->delete();
            }else{
                $query->where('id',$ids)->delete();
            }})->delete();
    }
    /*
     * 删除考试批次
     */
    public function deleteExam($id) {
        return BasicBatchModel::where('id',$id)->delete();
    }
    /*
     * 批量添加用户到考试批次
     */
    public function createUser($data){
        $res = $this->checkUser($data);
        if($res['code'] < 0){
            return $res;
        }
        $result = BasicMemberModel::insert($res['data']);;
        if($result){
            $res['msg'] = "添加成功";
            $res['code'] = 0;
            $res['data'] = [];
        }else{
            $res['msg'] = "添加失败";
            $res['code'] = -3;
            $res['data'] = [];
        }
        return $res;
    }
    /*
     * 检查添加用户并组成批量添加数组
     */
    public function checkUser($data){
        $site_id = getCurrentSiteId();
        $user_org = $this->getOrgIds();
        $arr_user = [];
        foreach ($data['group'] as $k=>$v){
            $result_user = UserModel::where("username",$v)->first();
            if(empty($result_user)){
                $arr_user[] = $v;
            }
        }
        if(count($arr_user) > 0){
            $res['msg'] = implode(",",$arr_user)."用户名不存在";
            $res['code'] = -4;
        }else{
            $names = UserModel::where("site_id","<>",$site_id)->whereIn("username",$data['group'])->pluck('username')->toArray();
            if(count($names) > 0){
                $res['msg'] = implode(",",$names)."不是本站点成员";
                $res['code'] = -1;
            }else{
                $org_ids = UserModel::whereIn("username",$data['group'])->select('username','org_id')->get();
                $arr_org = [];
                foreach ($org_ids as $k=>$v){
                    if(!in_array($v['org_id'],$user_org)){
                        $arr_org[] = $v['username'];
                    }
                }
                if(count($arr_org) > 0){
                    $res['msg'] = implode(",",$arr_org)."不是本站点成员";
                    $res['code'] = -5;
                }else{
                    $locked = UserModel::whereIn("username",$data['group'])->where("is_locked",1)->pluck("username")->toArray();
                    if(count($locked) > 0){
                        $res['msg'] = implode(",",$locked)."账户已被禁用";
                        $res['code'] = -6;
                    }else{
                        $ids = UserModel::whereIn("username",$data['group'])->pluck("id");
                        $user_id = BasicMemberModel::whereIn('user_id',$ids)->where("batch_id",$data['batch_id'])->pluck('user_id');
                        if(count($user_id) > 0){
                            $username = UserModel::whereIn("id",$user_id)->pluck("username")->toArray();
                            $res['msg'] = implode(",",$username)."已添加过";
                            $res['code'] = -2;
                        }else{
                            $time = time();
                            foreach ($ids as $k=>$v){
                                $arr[$k]["basic_id"] = $data["basic_id"];
                                $arr[$k]["batch_id"] = $data["batch_id"];
                                $arr[$k]["user_id"] = $v;
                                $arr[$k]["created_at"] = $time;
                                $arr[$k]["updated_at"] = $time;
                            }
                            $res['msg'] = "操作成功";
                            $res['code'] = 1;
                            $res['data'] = $arr;
                        }
                    }
                }

            }
        }
        return $res;
    }
    /*
     * 考试批次会员列表
     */
    public function getBasicMemberList($limit,$search){
        $res = BasicMemberModel::
            join('user as u','exam_batch_member.user_id','u.id')
            ->select('exam_batch_member.*','u.username as user_name')
            ->where(function($query) use ($search){
                if(!empty($search['batch_id'])){
                    $query->where("exam_batch_member.batch_id",$search['batch_id']);
                }
            })
            ->paginate($limit)->toArray();
        return $res;
    }
    /*
     * 获取当前用户组织机构
     */
    public function getOrgIds(){
        $data = getData("OrgDataTag");
        $arr = [];
        foreach ($data as $k=>$v){
            $arr[] = $v['id'];
        }
        return $arr;
    }
    /*
     * 获取当前用户科目权限
     */
    public function getCategoryIds(){
        $data = getData("CategoryDataTag");
        $arr = [];
        foreach ($data as $k=>$v){
            $arr[] = $v['id'];
        }
        return $arr;
    }
    /*
     * 当前用户管理的会员列表
     */
    public function getUserList($search){
        $org_ids = $this->getOrgIds();
        if($search['type'] == 2){
            $res = UserModel::
                leftjoin('post as p','user.post_id','p.id')
                ->join('org as o','user.org_id','o.id')
                ->join('user_profile as u','user.id','u.id')
                ->leftjoin('exam_batch_member as e','user.id','e.user_id')
                ->select("user.*","p.name as post_name","o.name as org_name","truename")
                ->where(function($query) use ($search){
                    if(!empty($search['post_id'])){
                        $query->where('post_id',$search['post_id']);
                    }
                    if(!empty($search['org_code'])){
                        $org_ids = $this->selectOrgData($search['org_code']);
                        $query->whereIn('org_id',$org_ids);
                    }
                    if(!empty($search['usergroup_id'])){
                        $ids = $this->selectUserGroupData($search['usergroup_id']);
                        $query->whereIn('user.id',$ids);
                    }
                })
                ->whereIn("user.org_id",$org_ids)
                ->where("is_locked",0)
                ->whereNull("e.user_id")
                ->get()->toArray();
        }else{
            $res = [];
        }
        return json_encode($res);
    }
    /*
     * 查询组织机构所有子项
     */
    public function selectOrgData($org_code){
        return OrgModel::where('code',"like",$org_code."%")->pluck('id');
    }
    /*
     * 查询用户组内部数据，并返回user_id数组
     */
    public function selectUserGroupData($group_id){
        $user = $this->getOrgIds();
        $list = UserGroupMember::where('group_id',$group_id)->get();
        foreach ($list as $k=>$v){
            if($v['type'] == "org"){
                if(!in_array($v['member_id'],$user)){
                   unset($list[$k]);
                }
            }
        }
        $arr = [];
        $result = [];
        foreach ($list as $k=>$v){
            switch ($v['type']){
                case 'org':
                    $org_ids = $this->selectOrgData($v['member_id']);
                    $arr[] = UserModel::whereIn('org_id',$org_ids)->pluck("id")->toArray();
                    break;
                case 'post':
                    $arr[] = UserModel::where('post_id',$v['member_id'])->pluck("id")->toArray();
                    break;
                case 'user':
                    $arr[] = $v['member_id'];
                    break;
            }
        }
        foreach ($arr as $k=>$v){
            if(is_array($v)){
                foreach ($v as $a=>$b){
                    $result[] = $b;
                }
            }else{
                $result[] = $v;
            }
        }
        return array_unique($result);
    }
    /*
     * 移除批次内用户
     */
    public function deleteUser($data){
        return BasicMemberModel::where("batch_id",$data['batch_id'])->where("user_id",$data['user_id'])->delete();
    }
    /*
     * 检查考场内是否有考试批次数据
     */
    public function checkDel($id){
        return BasicBatchModel::where(function($query) use ($id){
            if(is_array($id)){
                $query->whereIn("basic_id",$id);
            }else{
                $query->where("basic_id",$id);
            }
        })->count();

    }
    /*
     * 通过主键获取考场名称
     */
    public function getBasicName($basic_id){
        return BasicModel::where('id',$basic_id)->value("basic");
    }
    /*
     * 通过主键获取考试批次名称
     */
    public function getBatchName($batch_id){
        return BasicBatchModel::where('id',$batch_id)->value("name");
    }
}
